<template>
  <!-- 添加提现账户 银行卡 支付宝 -->
  <el-dialog class="pick-dialog" title="收款账户" :visible.sync="dialogVisible" :close-on-click-modal="false" append-to-body width="900px">
    <div class="back_list">
      <div class="my_cards flex">
        <div class="item flex" v-for="item in cardsList" :key="item.id">
          <span class="icon">
            <img v-if="item.collectionType==2" src="https://imgage.maimaihao.com/yuduhulian/erp/static/icon/zfblogo.png" alt="">
            <img v-if="item.collectionType==3" src="https://imgage.maimaihao.com/yuduhulian/erp/static/icon/bankcard.png" alt="">
          </span>
          <span class="account">{{item.collectionAccount}}</span>
          <span class="name">{{item.collectionUserName}}</span>
          <el-button v-if="userInfo.userId == shopInfo.adminId" type="text" @click="delItem(item.id)">删除</el-button>
        </div>
      </div>
      <div class="center" v-show="!showAdd" style="margin-top: 15px;">
        <el-button type="primary" @click="showAddFn" :loading="loading">添加账户</el-button>
      </div>

    </div>
    <div class="form-box" v-if="showAdd">

      <el-form :model="ruleForm" ref="ruleForm" label-width="100px" :rules="rules" class="demo-ruleForm">
        <el-form-item label="账户类型:" prop="collectionType">
          <el-select filterable v-model="ruleForm.collectionType" @change="typeChange">
            <el-option v-for="(item,key) in commonMaps.accountType" :key="key" :label="item" :value="key">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="ruleForm.collectionType==3" label="开户行:" prop="collectionAccountName">
          <el-input v-model="ruleForm.collectionAccountName" placeholder="开户行，例如：中国银行XXX支行"></el-input>
        </el-form-item>
        <el-form-item label="账户名称:" prop="collectionUserName">
          <el-input v-model="ruleForm.collectionUserName" placeholder="账户名称，例如：张三"></el-input>
        </el-form-item>
        <el-form-item label="账号:" prop="collectionAccount">
          <el-input v-model="ruleForm.collectionAccount" placeholder="收款账号，例如：6226322144212"></el-input>
        </el-form-item>

        <el-form-item label="验证码:" prop="dxyzm">
          <el-input v-model="ruleForm.dxyzm" placeholder="请输入验证码" style="width:120px"></el-input>
          <el-button style="margin-left:8px;width:100px" type="primary" class="yzm-btn" :disabled="timer !== 0" @click="sendYzm">
            <span v-if="timer">{{ timer }}秒</span>
            <span v-else>发送验证码</span>
          </el-button>

          <div v-if="timer">已向绑定手机{{ruleForm.phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')}}发送验证码</div>
          <div v-else>绑定手机:{{ruleForm.phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')}}</div>
        </el-form-item>
      </el-form>
      <div class="center">
        <el-button @click="showAdd=false">取消</el-button>
        <el-button type="primary" @click="submitForm('ruleForm')" :loading="loading">保存</el-button>
      </div>
    </div>


    <div v-if="showCaptchabox" style=" position: absolute;left: 250px;top: 155px;">
			<iframe :update-title="false" class="captcha-box" style="width: 350px;height: 325px;"
				:src="captchaUrl+'/index.html'"></iframe>
		</div>
  </el-dialog>
</template>

<script>
import myMoneyApi from "@/api/financeCenter/myMoney.js";
import { mapGetters } from "vuex";
import { getCodeImg, sendSMSCode, sendSMSCodeNew } from "@/api/login";
export default {
  data() {
    return {
      timer: 0,
      dialogVisible: false,
      loading: false,
      ruleForm: {
        userId: "",
        collectionType: "", //提现账户类型 1：微信 2：支付宝 3：银行卡
        collectionUserName: "",
        collectionAccount: "",
        collectionAccountName: "",
        phone: "",
        dxyzm: "",
        yzmRankey: "",
      },
      rules: {
        collectionType: [
          { required: true, message: "请选择", trigger: "change" },
        ],
        collectionAccountName: [
          { required: true, message: "请输入银行名称", trigger: "blur" },
        ],
        collectionAccount: [
          { required: true, message: "请输入收款账户", trigger: "blur" },
        ],
        collectionUserName: [
          { required: true, message: "请输入真实姓名", trigger: "blur" },
        ],
        dxyzm: [
          { required: true, message: "请输入短信验证码", trigger: "blur" },
        ],
      },
      cardsList: [],
      showAdd: false,

      showCaptchabox: false,
      captchaUrl: "https://captcha.maimaizhanghao.com",
      captchaPassId: "",
    };
  },
  created() {},
  computed: {
    ...mapGetters(["userInfo", "shopInfo"]),
  },
  methods: {
    open(user, type) {
      this.loading = false;
      if (this.shopInfo.authType >= 2) {
        let renzhengInfo;
        if (this.shopInfo.authType == 2) {
          renzhengInfo = JSON.parse(this.shopInfo.personInfo);
        } else {
          renzhengInfo = JSON.parse(this.shopInfo.corpInfo);
        }
           console.log(
          "%c Line:118 🍒 renzhengInfo",
          "color:#465975",
          renzhengInfo
        );

        if ( renzhengInfo&&renzhengInfo.phone) {
          this.ruleForm.phone = renzhengInfo.phone;
        }
        // renzhengInfo;
     
      } else {
        this.$confirm("店铺还未认证，请先进行实名认证！", "提示", {
          confirmButtonText: "立即认证",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            this.$emit("openAuthDialog");
          })
          .catch(() => {});
        return;
      }
      this.getList();

      this.dialogVisible = true;
    },
    xiaosuanFn(e) {
				let _this = this
				let data = e.data; //返回结果
				let origin = e.origin; //返回的域名
				if (origin == _this.captchaUrl) {
					if (data.type == "WEB_INVOKE_APPSERVICE") {
						const params = data.data.arg
						if (params && params.type == 'captchaMessage') {
							// 拿到验证通过的id
							_this.captchaPassId = params.id
							_this.showCaptchabox = false
							_this.sendYzm()
						}
						if (params && params.type == 'captchaClose') {
							// 关闭引入窗口
							_this.showCaptchabox = false
						}
					}
				}
			},
    // 开始添加账户
    showAddFn() {
      this.showAdd = true;
      this.loading = false;
      this.ruleForm = {
        userId: "",
        collectionType: "", //提现账户类型 1：微信 2：支付宝 3：银行卡
        collectionUserName: "",
        collectionAccount: "",
        collectionAccountName: "",
        phone: "",
        dxyzm: "",
        yzmRankey: "",
      };
      if (this.shopInfo.authType >= 2) {
        let renzhengInfo;
        if (this.shopInfo.authType == 2) {
          renzhengInfo = JSON.parse(this.shopInfo.personInfo);
        } else {
          renzhengInfo = JSON.parse(this.shopInfo.corpInfo);
        }
        if (renzhengInfo&&renzhengInfo.phone) {
          this.ruleForm.phone = renzhengInfo.phone;
        }
      }
      // if (this.shopInfo.authPhone) {
      //   this.ruleForm.phone = this.shopInfo.authPhone;
      // }
    },
    // 查询已绑定的收款账户
    async getList() {
      this.loading = true;
      let res1 = await myMoneyApi.getBackcardList({partyType:1});
      this.cardsList = res1.rows;
      this.loading = false;
    },
    // 删除一个收款账户
    delItem(id) {
      this.$confirm("确认删除该提现账户吗", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          myMoneyApi.delBackcardListOne(id).then((res) => {
            this.$message.success(res.msg);
            this.getList();
          });
        })
        .catch(() => {});
    },
    typeChange(e) {
      if (e == 1) {
        this.ruleForm.collectionAccountName = "微信";
      } else if (e == 2) {
        this.ruleForm.collectionAccountName = "支付宝";
      } else if (e == 3) {
        this.ruleForm.collectionAccountName = "";
      }
    },
    // 发送短信验证码
    sendYzm() {
    
      if (!/^1[3-9]\d{9}$/.test(this.ruleForm.phone)) {
        this.$message({
          type: "error",
          message: "手机号错误！",
        });
        return;
      }
    
      let obj = {
        phone: this.ruleForm.phone,
        type: "collection",
        id: this.captchaPassId,
      };
      sendSMSCodeNew(obj, {
        "s-tenant-id": this.userInfo.tenantId,
      }).then((res) => {
        if (res.code == 200) {
            window.removeEventListener('message', this.xiaosuanFn)
						this.timer = 60
						this.changeTimer()
						this.$message.success(res.msg)
						this.ruleForm.yzmRankey = res.data.yzmRankey
					} else if (res.code == 801) {
						// 需要滑块验证
            window.addEventListener("message", this.xiaosuanFn)
						this.showCaptchabox = true
					} else {
            this.$message.error(res.msg)
            window.removeEventListener('message', this.xiaosuanFn)
					}
      });
    },
    changeTimer() {
      if (this.timer > 0) {
        this.timer -= 1;
        if (this.timer > 0) {
          setTimeout(() => {
            this.changeTimer();
          }, 1000);
        }
      }
    },

    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.loading = true;
          myMoneyApi
            .addBankcard(this.ruleForm)
            .then((res) => {
              this.loading = false;
              this.$message({
                type: "success",
                message: res.msg,
              });
              if (res.code == 200) {
                this.showAdd = false;
                this.getList();
              }
            })
            .catch((err) => {});
        } else {
          //console.log("error submit!!");
          return false;
        }
      });
    },

    close(formName) {
      this.dialogVisible = false;
    },
  },
};
</script>
<style scoped lang="scss">
::v-deep .el-dialog__body {
  min-height: 500px;
}
.form-box {
  width: 450px;
  margin: 0 auto;
  border: 1px solid #e3e3e3;
  border-radius: 8px;
  padding: 15px;
  margin-top: 15px;
  background-color: #f7f7f7;
}

.center {
  text-align: center;
}
.my_cards {
  flex-wrap: wrap;
  img {
    width: 50px;
    margin-right: 15px;
  }
  .item {
    width: 360px;
    height: 60px;
    padding: 0 15px;
    border-radius: 10px;
    align-items: center;
    justify-content: space-between;
    box-shadow: 0 0 2px 0 rgba(0, 0, 0, 0.3);
    margin-bottom: 10px;
    margin-right: 15px;
    .account {
      font-size: 16px;
      font-weight: bold;
    }
    .name {
      font-size: 16px;
      font-weight: bold;
    }
  }
}
</style>
